# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        ret = []
        def find(root):
            if ret: return 0
            if not root: return 0
            cnt = 1 if root==p or root==q else 0
            cnt += find(root.left)
            cnt += find(root.right)
            if cnt==2 and not ret: ret.append(root)
            return cnt

        find(root)
        return ret[0]